/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-23
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.sys.web.system;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.hnas.core.dto.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.core.util.ExcelReader;
import com.hnas.core.util.ObjectUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.sys.core.util.UserUtils;
import com.hnas.sys.domain.ResourceType;
import com.hnas.sys.service.system.AuthorityService;
import com.hnas.sys.service.system.MenuPackageService;
import com.hnas.sys.service.system.ResourceService;
import com.hnas.sys.service.system.criteria.DTOSearchResource;
import com.hnas.sys.service.system.dto.DTOAuthority;
import com.hnas.sys.service.system.dto.DTOResource;
import com.hnas.sys.service.system.dto.DTOUser;

/**
 * @author 郑兴(zhengxing)
 *
 */
@Controller
@RequestMapping("/backend/system/resource")
public class ResourceController {
	private static final Cache cache = CacheManager.getInstance().getCache("systemCache");
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private AuthorityService authorityService;
	@Autowired
	private MenuPackageService menuPackageService;
	
	private Logger log = LoggerFactory.getLogger(ResourceController.class);
	
	/**
	 * <pre>跳转到资源管理页面，</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午4:20:03
	 * @param model
	 * @return
	 */
//	@RequestMapping("/resource")
//	public String goToResource(ModelMap model) {
//		model.put("resources", loadResource());
//		List<DTOAuthority> roleLists = authorityService.getAllAuthorities();
//		model.put("roleLists", roleLists);
//		return "backend/system/resource";
//	}
	
	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request,
			@ModelAttribute("criteria") DTOSearchResource criteria) {

		try {
//			String page = request.getParameter((new ParamEncoder("values")
//					.encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
//			/**
//			 * if (!"false".equals(request.getParameter("firstInvoke"))) {
//			 * modelMap.put("resultSize", 0); return
//			 * "backend/product/searchProviders"; }
//			 **/
//			if (null == page) {
//				criteria.setPageNo(1);
//			} else {
//				criteria.setPageNo(Integer.parseInt(page));
//			}
			criteria.setTotalCount(-1);
			DTOUser user = UserUtils.getCurrentUser();

			DTOPagedList<DTOResource> pg = this.resourceService.search(criteria);
//			modelMap.put("citys", pg.getList());
			modelMap.put("pg", pg);
			modelMap.put("resultSize", pg.getTotalCount());
			modelMap.put("dto", criteria);
		} catch (Exception e) {
			log.error("", e);
			modelMap.put("resultSize", 0);
		}
		modelMap.put("pageTitle", "菜单维护");
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("name","name","菜单名称",false,125));
		beans.add(new DataBean("resource","resource","资源url",false,255));
		beans.add(new DataBean("description","description","描述",true,255));
		beans.add(new DataBean("priority","priority","排序","int",true));
		beans.add(new DataBean("operateType","operateType","操作类型","int",true));
		modelMap.put("beans", beans);
		
		List<DTOAuthority> roleLists = authorityService.getAllAuthorities();
		modelMap.put("roleLists", roleLists);
		
		modelMap.put("packageLists", this.menuPackageService.loadAll());
		
		
		return "backend/system/resource/listResources";
	}
	
	/**
	 * <pre>加载所有资源，以Json格式返回</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午4:23:51
	 * @return
	 */
	@RequestMapping("/resourceOfJson")
	@ResponseBody
	public Object loadResourceForJson() {
		return loadResource();
	}
	
	/**
	 * <pre>加载所有资源</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午4:31:06
	 * @return
	 */
	private List<DTOResource> loadResource() {
		/*从数据库加载所有资源*/
		if(null == cache.get("resources")) {
			List<DTOResource> resources = resourceService.loadAllResource();
			cache.put(new Element("resources", resources));
			return resources;
		}
		/*从缓存加载资源*/
		return (List<DTOResource>) cache.get("resources").getObjectValue();
	}
	
	/**
	 * <pre>添加或者更新资源信息</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月28日 下午4:22:11
	 * @param resource
	 * @param response
	 * @return
	 */
//	@RequestMapping(value="resource/add")
//	@ResponseBody
//	public String addResource(@ModelAttribute("resource")DTOResource resource, HttpServletResponse response) {
//		String result = "fail";
//		try {
//			
//			resourceService.saveOrUpdate(resource);
//			result = "success";
//		} catch (Exception e) {
////			e.printStackTrace();
//			result="fail:"+e.getMessage();
//		}
////		doAjaxResponse(response, result);
//		return result;
//	}
	
//	@RequestMapping(value="resource/{id}",method=RequestMethod.POST)
//	@ResponseBody
//	public Object loadResource(@PathVariable("id") Long id) {
//		DTOResource dto = this.resourceService.load(id);
//		return dto;
//	}
	
	@RequestMapping(value = "show/{id}", method = RequestMethod.POST)
	@ResponseBody
	public DTOResource show(@PathVariable("id") Long id) {
		DTOResource dto = this.resourceService.load(id);
		return dto;
	}

	@RequestMapping(value = "disable/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") Long id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		this.resourceService.disable(id);
		res.setResult(1);
		return res;
	}
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse add( DTOResource dto) {
		return this.save(dto);
	}
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse save( DTOResource dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			this.resourceService.saveOrUpdate(dto,false);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
	
//	@RequestMapping(value="resource/{id}",method=RequestMethod.DELETE)
//	@ResponseBody
//	public Object deleteResource(@PathVariable("id") Long id) {
//		String result = "success";
//		try {
//			resourceService.disable(id);//.delete(id);
//		} catch (Exception e) {
//			result = "fail";
//		}
//		return result;
//	}
	
//	@RequestMapping(value="/upload",method=RequestMethod.POST)
//    public String ajaxUpload(@RequestParam("file") CommonsMultipartFile image,HttpServletRequest request) throws IOException
//    {
//        String path = request.getRealPath("/upload");
//        request.setAttribute("name",image.getOriginalFilename());
//        request.setAttribute("img","<img src='/dt/upload/"+image.getOriginalFilename()+"'></img>");
//        FileCopyUtils.copy(image.getBytes(),new File(path+"/"+image.getOriginalFilename())); 
//        return "ok";
//    }
//	
	/**
	 * <pre>返回执行结果</pre>
	 * @Auther 郑兴(zhengxing)
	 * @Date 2013年7月26日
	 * @param response
	 * @param result
	 */
//	public void doAjaxResponse(HttpServletResponse response, String result) {
//		try {
//			response.setContentType("text/html");
//			PrintWriter out = response.getWriter();
//			out.flush();
//			out.print(result);
//			out.flush();
//			out.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	@RequestMapping(value = "upload")
	public BaseAjaxResponse upload(
			//@RequestParam(value = "formFile") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response
			) {//ModelMap model
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			MultipartRequest multipartRequest = (MultipartRequest)request;
			MultipartFile file  =  multipartRequest.getFile("formFile");
			if(file.getSize()>2*1000*1000){
				throw new Exception("上传文件过大！");
			}
			List<DTOResource> ls = this.parseData(file.getInputStream(),
					file.getOriginalFilename());
			for (DTOResource dto:ls){
				this.resourceService.saveOrUpdate(dto,true);
			}
//			this.airportService.saveResources(ls);
			// this.airportService.refreshResources();
			res.setResult(1);
//			return "/backend/common/showSucess";
		} catch (Exception e) {
//			e.printStackTrace();
//			model.put("errorMsg", e.getMessage());
			res.setErrorMessage("错误："+e.getMessage());
//			return "/backend/common/showErr";
		}
		try {
			String s = ObjectUtil.getMapperInstance(false).writeValueAsString(res);
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();				
			out.print(s);
			out.flush();
			out.close();
			return null;
		} catch (Exception e) {
//			e.printStackTrace();
			log.error("",e);
		}
		return res;
	}

	private List<DTOResource> parseData(InputStream input,String fileName){
		List<DTOResource> ls = new ArrayList<DTOResource>();
		List<String[]> datas = null;
//		if (!xlsx){
				ExcelReader reader = new ExcelReader(input,fileName);
				datas = reader.getAllData(0);	
//		}else{
//			ExcelReader10 reader = new ExcelReader10(input);
//			datas = reader.getAllData(0);
//		}
		int i=0;
		for (String[] arr:datas){			
			i++;
			if (i==1)
				continue;
			if (StringUtil.isEmpty(arr[0]))
				continue;
			DTOResource dto = new DTOResource();
			int j=0;

			dto.setPackgeName(arr[j++]);
			dto.setName(arr[j++]);
			dto.setResource(arr[j++]);			
			dto.setOperateType(Integer.parseInt(arr[j++]));
			dto.setType("页面".equals(arr[j++])?ResourceType.PAGE:ResourceType.METHOD);
			dto.setPriority(Integer.parseInt(arr[j++]));
//			config.setResourceEName(arr[j++]);
//			DTOMenuPackage rg = new DTOMenuPackage();
//			rg.setCityName(arr[j++]);
//			config.setDtoCity(rg);
			
//			config.setValid("是".equals(arr[j++]));
			ls.add(dto);
//			}
		}
		return ls;
	}
	
	/**
	 * <pre>绑定校验器</pre>
	 * @Auther 郑兴(zhengxing)
	 * @Date 2013年7月25日
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
//		binder.setValidator(new ResourceValidator());
	}


}
